package com.duowan.realtime.computing.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;




/**
 * 加载配置文件的工具类,加载不同环境的配置文件
 * application-dev.properties 开发环境
 * application-prod.properties 生产环境
 * 
 * @author badqiu
 *
 */
public class ConfigLoader {

	private static Logger logger = LoggerFactory.getLogger(ConfigLoader.class);
	private static Properties properties = new Properties();
	
	static {
		String appMode = System.getProperty("appMode","dev");
		setAppMode(appMode);
	}
	
	public static enum AppMode {
		prod,dev,test
	}
	
	public static boolean isDevMode() {
		if("dev".equals(properties.get("appMode"))) {
			return true;
		}
		return false;
	}
	
	public static void setAppMode(String appMode){
		properties.put("appMode", appMode);
		properties.clear();
		String location = "classpath:conf/application-"+appMode+".properties";
		Properties props = loadPropertiesByEnv(location);
		logger.info("loaded config:"+location+" properties:"+props);
		properties.putAll(props);
	}

	public static Properties loadPropertiesByEnv(String location) {
		InputStream input = getInputStream(location);
		try {
			Properties properties = new Properties();
			properties.load(new InputStreamReader(input,"UTF-8"));
			return properties;
		}catch(IOException e) {
			throw new RuntimeException("load file error,location:"+location,e);
		}finally {
			IOUtils.closeQuietly(input);
		}
	}
	
	public static String getProperty(String key){
		return properties.getProperty(key);
	}
	
	public static Properties getProperties() {
		return properties;
	}

	public static void initByStormPrepare(Map stormConf) {
		logger.info("init ConfigLoader by stormConf:"+stormConf);
		for(Object key : stormConf.keySet()) {
			Object value = stormConf.get(key);
			if(key == null || value == null) {
				continue;
			}
			properties.put(key, value);
		}
	}
	
	public static InputStream getInputStream(String location) {
		try {
			Resource[] resources = new PathMatchingResourcePatternResolver().getResources(location);
			for(Resource r : resources) {
				InputStream input = r.getInputStream();
				return input;
			}
		}catch(IOException e) {
			throw new RuntimeException("error getInputStream by location:"+location,e);
		}
		throw new RuntimeException("not found any InputStream by location:"+location);
	}
	
}

